import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  Button,
  TouchableHighlight,
  FlatList,
  RefreshControl,
} from 'react-native';
import { Popover, PopoverContainer } from 'react-native-simple-popover';
import { StackNavigator, TabNavigator } from 'react-navigation';
import ScrollableTabView, { ScrollableTabBar } from 'react-native-scrollable-tab-view';
import ViewUtils from '../util/ViewUtils';
import FavoriteDao from '../expand/dao/FavoriteDao'
import Utils from '../util/Utils'
import ProjectModel from '../model/ProjectModel';
import DataRepository, { FLAG_STORAGE } from '../expand/dao/DataRepository';
import RepositoryCell from '../common/RepositoryCell'
import TrendingRepoCell from '../common/TrendingRepoCell'

export default class TestPage extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerTitle: '收藏',
    tabBarLabel: '收藏',
    headerRight: ViewUtils.getRightButton(() => { navigation.state.params.onMenu() }),
    headerStyle: { backgroundColor: '#2196F3' },
    headerTitleStyle: { alignSelf: 'center', color: 'white' },
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('../../res/images/ic_favorite.png')}
        style={[styles.icon, { tintColor: '#ffffff' }]}
      />
    ),
  });

  constructor(props) {
    super(props);
  }

  // 需要延迟加载 ScrollableTabView
  componentDidMount() {
    this.timer = setTimeout(() => {
      this.setState({
        delay: true
      });
    }, 100);
  }

  render() {
    return (
      <ScrollableTabView style={styles.container}
        tabBarBackgroundColor="#2196F3"
        tabBarInactiveTextColor="mintcream"
        tabBarBackgroundColor="#2196F3"
        tabBarUnderlineStyle={{ backgroundColor: '#e7e7e7', height: 2 }}
        locked={false}
        renderTabBar={() => <ScrollableTabBar />}>
        <FavoriteTab {...this.props} tabLabel='最热' flag={FLAG_STORAGE.flag_popular} />
        <FavoriteTab {...this.props} tabLabel='趋势' flag={FLAG_STORAGE.flag_trending} />
      </ScrollableTabView>
    );
  }
}

class FavoriteTab extends Component {
  constructor(props) {
    super(props);
    this.favoriteDao = new FavoriteDao(this.props.flag);
  }

  // 加载数据
  componentDidMount() {
    this.loadData();
  }

  componentWillReceiveProps(nextProps) {
    this.loadData();
  }

  state = {
    data: '',
    isLoading: true,
  }

  loadData() {
    this.favoriteDao.getAllItems()
      .then((items) => {
        var resultData = [];
        for (var i = 0, len = items.length; i < len; i++) {
          resultData.push(new ProjectModel(items[i], true));
        }
        this.setState({
          isLoading: false,
          data: resultData,
        })
      })
      .catch((error) => {
        this.setState({
          isLoading: false,
        })
      })
  }

  onSelect(ProjectModel) {
    console.log(ProjectModel);
    if (this.props.flag === FLAG_STORAGE.flag_popular) {
      this.props.navigation.navigate('RepositoryDetail', {
        title: ProjectModel.item.full_name,
        url: ProjectModel.item.html_url,
      });
    } else {
      this.props.navigation.navigate('RepositoryDetail', {
        title: ProjectModel.item.fullName,
      });
    }
    // console.log(projectModel);
    // this.props.navigation.navigate('RepositoryDetail', {
    //   title: ProjectModel.item.full_name,
    //   url: ProjectModel.item.html_url !== null ? ProjectModel.item.html_url : null,
    // })
  }



  // 渲染每一项
  renderItem(item) {
    let CellComponent = this.props.flag === FLAG_STORAGE.flag_popular ? RepositoryCell : TrendingRepoCell;
    return <CellComponent
      projectModel={item}
      data={item} onSelect={() => this.onSelect(item)}
      onFavorite={(item, isFavorite) => this.onFavorite(item, isFavorite)}
    />
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => this.renderItem(item)}
          // 用index作为key
          keyExtractor={(item, index) => index}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isLoading}
              // 重新刷新
              onRefresh={() => this.loadData()}
              // 刷新图片颜色
              colors={['#2196F3']}
              tintColor={'#2196F3'}
              title={'Loading......'}
            />
          }
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  text: {
    fontSize: 22
  },
  icon: {
    height: 22,
    width: 22,
  },
  loading: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
})
